#!/bin/bash

# 便签与新闻功能 API 测试脚本
# 使用方法: ./test_api.sh [BASE_URL]
# 示例: ./test_api.sh http://localhost:8080

BASE_URL=${1:-"http://localhost:8080"}
TOKEN=""

echo "=== 智慧农业系统 - 便签与新闻功能 API 测试 ==="
echo "测试服务器: $BASE_URL"
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# 测试函数
test_api() {
    local name="$1"
    local method="$2"
    local url="$3"
    local data="$4"
    local expected_code="$5"
    local headers="$6"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    echo -n "测试 $name ... "
    
    if [ -n "$headers" ]; then
        response=$(curl -s -w "%{http_code}" -X "$method" "$BASE_URL$url" \
                   -H "Content-Type: application/json" \
                   -H "$headers" \
                   -d "$data")
    else
        response=$(curl -s -w "%{http_code}" -X "$method" "$BASE_URL$url" \
                   -H "Content-Type: application/json" \
                   -d "$data")
    fi
    
    http_code="${response: -3}"
    body="${response%???}"
    
    if [ "$http_code" = "$expected_code" ]; then
        echo -e "${GREEN}✓ 通过${NC} (HTTP $http_code)"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        
        # 如果是登录接口，提取token
        if [[ "$url" == "/api/auth/login" && "$http_code" = "200" ]]; then
            TOKEN=$(echo "$body" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
            echo "  获取到Token: ${TOKEN:0:20}..."
        fi
    else
        echo -e "${RED}✗ 失败${NC} (期望: $expected_code, 实际: $http_code)"
        echo "  响应: $body"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
}

echo "1. 测试用户认证功能"
echo "===================="

# 测试用户注册
test_api "用户注册" "POST" "/api/auth/register" \
    '{"username":"testuser_'$(date +%s)'","passwordMd5":"e10adc3949ba59abbe56e057f20f883e"}' \
    "200"

# 测试用户登录
test_api "用户登录" "POST" "/api/auth/login" \
    '{"username":"testuser","passwordMd5":"e10adc3949ba59abbe56e057f20f883e"}' \
    "200"

echo ""
echo "2. 测试便签功能"
echo "==============="

if [ -n "$TOKEN" ]; then
    # 测试创建便签
    test_api "创建便签" "POST" "/api/notes" \
        '{"title":"测试便签","content":"这是一个测试便签的内容"}' \
        "200" "Authorization: Bearer $TOKEN"
    
    # 测试获取便签列表
    test_api "获取便签列表" "GET" "/api/notes?page=0&size=10" \
        "" "200" "Authorization: Bearer $TOKEN"
    
    # 测试搜索便签
    test_api "搜索便签" "GET" "/api/notes?keyword=测试&page=0&size=10" \
        "" "200" "Authorization: Bearer $TOKEN"
else
    echo -e "${YELLOW}跳过便签测试 - 需要有效的Token${NC}"
fi

echo ""
echo "3. 测试新闻功能"
echo "==============="

# 测试获取新闻列表（无需登录）
test_api "获取新闻列表" "GET" "/api/news?page=0&size=10" \
    "" "200"

# 测试搜索新闻
test_api "搜索新闻" "GET" "/api/news?keyword=智慧农业&page=0&size=10" \
    "" "200"

# 测试获取新闻详情
test_api "获取新闻详情" "GET" "/api/news/1" \
    "" "200"

# 测试获取新闻评论
test_api "获取新闻评论" "GET" "/api/news/1/comments?page=0&size=20" \
    "" "200"

if [ -n "$TOKEN" ]; then
    # 测试点赞新闻
    test_api "点赞新闻" "POST" "/api/news/1/like" \
        "" "200" "Authorization: Bearer $TOKEN"
    
    # 测试发表评论
    test_api "发表评论" "POST" "/api/news/1/comments" \
        '{"content":"这是一条测试评论"}' \
        "200" "Authorization: Bearer $TOKEN"
else
    echo -e "${YELLOW}跳过需要登录的新闻功能测试${NC}"
fi

echo ""
echo "4. 测试系统健康状态"
echo "==================="

# 测试获取作物选项（无需登录）
test_api "获取作物选项" "GET" "/api/crops/options" \
    "" "200"

echo ""
echo "=== 测试结果汇总 ==="
echo "总测试数: $TOTAL_TESTS"
echo -e "通过: ${GREEN}$PASSED_TESTS${NC}"
echo -e "失败: ${RED}$FAILED_TESTS${NC}"

if [ $FAILED_TESTS -eq 0 ]; then
    echo -e "${GREEN}🎉 所有测试通过！${NC}"
    exit 0
else
    echo -e "${RED}❌ 有 $FAILED_TESTS 个测试失败${NC}"
    exit 1
fi
